/*
 * @Author:
 * @Date: 2022-11-24 13:56:00
 * @LastEditors:
 * @LastEditTime: 2022-11-28 09:58:53
 * @FilePath: \immoka-admin\src\router\index.js
 * @Description:
 *
 * Copyright (c) 2022 by  , All Rights Reserved.
 */
import Vue from 'vue'
import Router from 'vue-router'
import { Message } from 'element-ui'
import commonRouter from '@/router/common'
import { getDeadline } from '@/utils/auth'
import systemManage from './modules/system-manage'
import profitManage from './modules/profit-manage'
import unionManage from './modules/union-manage'

Vue.use(Router)

const ctx = require.context('./modules', true, /\.js$/)
const constant = ctx.keys().reduce((modules, modulePath) => {
  modules.push(ctx(modulePath).default)
  return modules
}, [])

export const asyncRoutes = [
  profitManage,
  unionManage,
  systemManage,
  { path: '*', redirect: '/404', hidden: true }
]

const router = new Router({
  mode: 'history',
  base: '/admin/moka',
  scrollBehavior: () => ({ y: 0 }),
  routes: [...constant, ...commonRouter]
})

function getCookie(name) {
  let cookieValue = null
  if (document.cookie && document.cookie !== '') {
    let cookies = document.cookie.split(';')
    for (let i = 0; i < cookies.length; i++) {
      let cookie = cookies[i].trim()
      // 判断这个cookie的参数名是不是我们想要的
      if (cookie.substring(0, name.length + 1) === name + '=') {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1))
        break
      }
    }
  }
  return cookieValue
}

router.beforeEach((to, from, next) => {
  let nowTime = new Date().getTime()

  if (to.path === '/login') {
    next()
  } else if (to.path === '/') {
    next({ path: '/login' })
  } else {
    let token = getCookie('Admin-Token')
    let deadline = getDeadline()
    if (!token || deadline < nowTime) {
      Message({
        message: '登录过期，请重新登录！',
        type: 'error',
        duration: 3 * 1000
      })
      return next('/login')
    }
    next()
  }
})

export default router
